package com.weic.easycache.task;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.weic.easycache.exception.SdCardNotMountedException;
import com.weic.easycache.framework.biz.IImgBiz;
import com.weic.easycache.utils.FileNameUtils;

public class ImgDlodTask extends AbsTask {
	private String[] mUrls;
	private final String mImgCtgy;
	private final IImgBiz<?> mBiz;
	private final boolean mToBitmap;
	private boolean mIrgnoreCache;
	private final boolean mNeedful;

	/**@param irgnoreCache	忽略本地磁盘缓存。注意这个跟Param.irgnoreCache不同，后者是内存缓存**/
	public ImgDlodTask(Context context, int id, String[] urls, String imgCategory,
			IImgBiz<?> biz, boolean toBitmap, boolean irgnoreCache, boolean needful, boolean canIrgnore) {
		super(context, id, biz, canIrgnore);
		mUrls = urls;
		mImgCtgy = imgCategory;
		mBiz = biz;
		mToBitmap = toBitmap;
		mIrgnoreCache = irgnoreCache;
		mNeedful = needful;
	}

	@Override
	protected boolean doSomething() throws Exception {
		if(!isExcuteAgain()) {
			updateUrls();
			if(mUrls == null) return false;
		}

		if(!isExcuteAgain() && !mNeedful) {
			queueBgTask(this);
		}else {
			setProgressCount(mUrls.length);

			Map<String, String> paths = new HashMap<String, String>();
			Map<String, Bitmap> bitmaps = new HashMap<String, Bitmap>();
			for(String url : mUrls) {
				String fileName = getCacheFileName(url);
				if(fileName != null) {
					if(mIrgnoreCache || !isExists(fileName)) {
						dlodImage(url, fileName);
					}
					if(isExists(fileName)) {
						if(mToBitmap) {
							Bitmap bmp = loadBitmap(url);
							if(bmp != null) {
								bitmaps.put(url, bmp);
								mBiz.update(mId, url, bitmaps);	//每完成一个，都要更新一次
							}
						}else {
							String path = getImagePath(fileName);
							if(path != null) {
								paths.put(url, path);
								mBiz.update(mId, url, paths);
							}
						}
					}
				}
				increaseProgress();
			}
		}
		return true;
	}

	private String getCacheFileName(String url) {
		String name = null;
		if(url != null && url.length() > 0 && url.startsWith("http")) {
			//用文件名的好处是，当服务端换了图片后（通常不会用相同文件名），能够直接知道是换了图片
			name = FileNameUtils.getFileNameFromUrl(url);
			if(name != null && name.length() > 0) {
				name = mImgCtgy + "_" + name;
			}else {
				name = null;
			}
		}
		return name;
	}

	private Bitmap loadBitmap(String fileName) {
		try {
			return mLocalAces.readImage(fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SdCardNotMountedException e) {
			e.printStackTrace();
		}
		return null;
	}

	private boolean isExists(String fileName) {
		return mLocalAces.isImageExists(fileName);
	}

	private String getImagePath(String fileName) {
		return mLocalAces.getImagePath(fileName);
	}

	private void dlodImage(String imgUrl, String fileName) {
		InputStream in = null;
		try {
			URL url = new URL(imgUrl);
			//URLConnection conn = url.openConnection();
			in = url.openStream();//conn.getInputStream();
			Bitmap bmp = BitmapFactory.decodeStream(in, null, null);
			mLocalAces.saveImage(fileName, bmp);
			bmp.recycle();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(in != null) try { in.close(); }catch(Exception e) { e.printStackTrace(); }
		}
	}

	private void updateUrls() {
		String[] newUrls = mBiz.fetchImgUrls(mId);

		if(newUrls == null || newUrls.length == 0) newUrls = null;
		if(mUrls == null || mUrls.length == 0) {
			mUrls = newUrls;
			newUrls = null;
		}
		if(mUrls == null) return;

		List<String> list = new ArrayList<String>();
		if(newUrls == null) {
			cleanRepeated(mUrls);
			for(String url : mUrls) {
				if(url != null) list.add(url);
			}
			mUrls = list.toArray(new String[list.size()]);
		}else {
			cleanRepeated(mUrls);
			cleanRepeated(newUrls);
			if(newUrls.length > mUrls.length) {
				String[] array = mUrls;
				mUrls = newUrls;
				newUrls = array;
			}
			for(int i=0; i<mUrls.length; i++) {
				if(mUrls[i] == null) continue;
				for(int j=0; j<newUrls.length; j++) {
					if(newUrls[j] == null) continue;
					if(mUrls[i].equalsIgnoreCase(newUrls[j])) newUrls[j] = null;
				}
			}
			for(String url : mUrls) {
				if(url != null) list.add(url);
			}
			for(String url : newUrls) {
				if(url != null) list.add(url);
			}
			mUrls = list.toArray(new String[list.size()]);
		}
		if(mUrls == null || mUrls.length == 0) mUrls = null;
	}

	private void cleanRepeated(String[] array) {
		for(int i=0; i<array.length; i++) {
			if(array[i] == null) continue;
			if(array[i].trim().length() == 0) {
				array[i] = null;
				continue;
			}
			for(int j=i+1; j<array.length; j++) {
				if(array[j] == null) continue;
				if(array[j].trim().length() == 0) {
					array[j] = null;
					continue;
				}
				if(array[i].equalsIgnoreCase(array[j])) array[j] = null;
			}
		}
	}
}
